// 整个项目单击事件的管理类
import * as THREE from 'three'
export class ClickHandler {
  // 单例模式（静态/类方法）：这个类被调用n次也只会产生同一个实例对象
  static getInstance() {
    if (!this.instance) {
      // 自由运行时 第一次才会进入
      this.instance = new ClickHandler()//实例化对象
    }

    return this.instance
  }
  init(camera) {
    this.camera = camera
    this.list = [] // 光线投射交互计算的物体
    this.map = new Map()

    // 设置点击事件
    const raycaster = new THREE.Raycaster()
    const pointer = new THREE.Vector2()
    const app = document.querySelector('.app')
    window.addEventListener('click', (e) => {
      pointer.x = (e.clientX / app.clientWidth) * 2 - 1
      pointer.y = - (e.clientY / app.clientHeight) * 2 + 1
      raycaster.setFromCamera(pointer, this.camera)
      const list = raycaster.intersectObjects(this.list)
      list.forEach(obj => {
        const fn = this.map.get(obj.object)
        fn(obj.object)
      })
    })
  }
  // 传入需要点击的物体和函数体
  addMesh(mesh, fn) {
    this.list.push(mesh)
    this.map.set(mesh, fn)
  }
}